﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OOSE_TDD
{
    public class ShoppingCart
    {
        private Dictionary<String, LineItem> shoppingCartItems = new Dictionary<String, LineItem>();
        private Customer owningCustomer;

        public Customer OwningCustomer
        {
            get { return owningCustomer; }
            set { owningCustomer = value; }
        }

        public Dictionary<String, LineItem> ShoppingCartItems
        {
            get { return shoppingCartItems; }
        }

        public void addArticle(Article article)
        {
            LineItem lineItemFromCart = findLineItem(article.ArticleName);
            if (lineItemFromCart != null)
            {
                lineItemFromCart.NumberOfAnArticle++;
            }
            else
            {
                LineItem newItem = new LineItem();
                newItem.Article = article;
                newItem.NumberOfAnArticle = 1;
                shoppingCartItems.Add(article.ArticleName, newItem);
            }
        }

        public void removeArticle(Article article)
        {
            LineItem lineItemFromCart = findLineItem(article.ArticleName);

            if ((lineItemFromCart != null) && (lineItemFromCart.NumberOfAnArticle > 1))
            {
                lineItemFromCart.NumberOfAnArticle--;
            }
            else
            {
                shoppingCartItems.Remove(article.ArticleName);
            }
        }

        private LineItem findLineItem(String articleName)
        {
            LineItem foundLineItem = null;

            if (shoppingCartItems.ContainsKey(articleName))
            {
                foundLineItem = shoppingCartItems[articleName];
            }

            return foundLineItem;
        }


        public decimal getGrossPrice()
        {
            return shoppingCartItems.Sum(
                n =>
                {
                    return (n.Value.Article.NetPrice * (1 + n.Value.Article.TaxRate))
                        * n.Value.NumberOfAnArticle;
                });
        }

        public decimal getNetPrice()
        {
            return shoppingCartItems.Sum(
                n =>
                {
                    return n.Value.Article.NetPrice * n.Value.NumberOfAnArticle;
                });
        }
    }
}
